﻿using Aspose.Cells;
using Aspose.Slides;
using Aspose.Words;
using Aspose.Words.Saving;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WordSaveOptions = Aspose.Words.Saving.PdfSaveOptions;

namespace Xuxml.Tools.Office
{
    /// <summary>
    /// Office管理
    /// </summary>
    public class OfficeManager
    {
        /// <summary>
        /// Office文件扩展名
        /// </summary>
        public static readonly string[] OfficeFileExtension = { "doc", "docx", "rtf", "ppt", "pptx", "xls", "xlsx" };
        private static readonly string[] WordFileExtension = { "doc", "docx", "rtf" };
        private static readonly string[] ExcelFileExtension = { "xls", "xlsx" };
        private static readonly string[] PPTFileExtension = { "ppt", "pptx" };

        /// <summary>
        /// 将Office文件转化为pdf临时文件，若不是office文件则返回原文件
        /// </summary>
        /// <param name="path">源文件</param>
        /// <param name="password">若需要PDF加密，则填写该项</param>
        /// <returns>Pdf临时文件</returns>
        public static string ToPDF(string path, string password = null)
        {
            if (!File.Exists(path))
            {
                throw new Exception("文件不存在");
            }
            var extensionName = Path.GetExtension(path).Replace(".", "").ToLower();

            if (!OfficeFileExtension.Contains(extensionName))
            {
                return path;
            }
            var toPath = Path.GetTempPath() + Guid.NewGuid().ToString().Replace("-", "") + ".pdf";

            if (WordFileExtension.Contains(extensionName))
            {
                return WordToPDF(path, toPath);
            }

            if (ExcelFileExtension.Contains(extensionName))
            {
                return ExeclToPDF(path, toPath);
            }

            if (PPTFileExtension.Contains(extensionName))
            {
                return PPTToPDF(path, toPath);
            }
            return path;

        }

        /// <summary>
        /// 把from位置的文件转成to位置的pdf
        /// </summary>
        /// <param name="from">源文件</param>
        /// <param name="to">目标文件，例 C:/A.pdf  </param>
        /// <param name="password">若需要PDF加密，则填写该项</param>
        public static void ToPDF(string from, string to, string password = null)
        {

            if (!File.Exists(from))
            {
                throw new Exception("文件不存在");
            }
            var extensionName = Path.GetExtension(from).Replace(".", "").ToLower();

            if (!OfficeFileExtension.Contains(extensionName))
            {
                return;
            }

            if (WordFileExtension.Contains(extensionName))
            {
                WordToPDF(from, to);
            }

            if (ExcelFileExtension.Contains(extensionName))
            {
                ExeclToPDF(from, to);
            }

            if (PPTFileExtension.Contains(extensionName))
            {
                PPTToPDF(from, to);
            }
            return;
        }

        /// <summary>
        /// Word转PDF
        /// </summary>
        /// <param name="wordPath">源文件</param>
        /// <param name="toPath">目标文件，例 C:/A.pdf  </param>
        /// <param name="password">若需要PDF加密，则填写该项</param>

        /// <returns></returns>
        private static string WordToPDF(string wordPath, string toPath, string password = null)
        {
            try
            {
                Document doc = new Document(wordPath);
                //保存为PDF文件，此处的SaveFormat支持很多种格式，如图片，epub,rtf 等等

                //权限这块的设置成不可复制
                WordSaveOptions saveOptions = new WordSaveOptions();
                if (!string.IsNullOrEmpty(password))
                {
                    // Create encryption details and set owner password.
                    PdfEncryptionDetails encryptionDetails = new PdfEncryptionDetails(string.Empty, password, PdfEncryptionAlgorithm.RC4_128);
                    // Start by disallowing all permissions.
                    encryptionDetails.Permissions = PdfPermissions.DisallowAll;
                    // Extend permissions to allow editing or modifying annotations.
                    encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly;
                    saveOptions.EncryptionDetails = encryptionDetails;
                    // Render the document to PDF format with the specified permissions.
                }


                doc.Save(toPath, saveOptions);
                return toPath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Excel转PDF
        /// </summary>
        /// <param name="excelPath">源文件</param>
        /// <param name="toPath">目标文件，例 C:/A.pdf  </param>
        /// <param name="password">若需要PDF加密，则填写该项</param>

        /// <returns></returns>
        private static string ExeclToPDF(string excelPath, string toPath, string password = null)
        {
            try
            {

                Aspose.Cells.Workbook xls = new Aspose.Cells.Workbook(excelPath);
                Aspose.Cells.PdfSaveOptions xlsSaveOption = new Aspose.Cells.PdfSaveOptions();
                xlsSaveOption.SecurityOptions = new Aspose.Cells.Rendering.PdfSecurity.PdfSecurityOptions();
                #region pdf 加密
                //PDF加密功能
                if (!string.IsNullOrEmpty(password))
                {
                    xlsSaveOption.SecurityOptions.UserPassword = string.Empty;
                    xlsSaveOption.SecurityOptions.OwnerPassword = password;
                }

                #endregion
                xlsSaveOption.SecurityOptions.ExtractContentPermission = false;
                xlsSaveOption.SecurityOptions.PrintPermission = false;
                xlsSaveOption.AllColumnsInOnePagePerSheet = true;

                xls.Save(toPath, xlsSaveOption);

                Console.WriteLine("转换成功!");
                return toPath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// PPT转PDF
        /// </summary>
        /// <param name="pptPath">源文件</param>
        /// <param name="toPath">目标文件，例 C:/A.pdf  </param>
        /// <param name="password">无法加密</param>
        /// <returns></returns>
        private static string PPTToPDF(string pptPath, string toPath, string password = null)
        {
            try
            {
                Presentation ppt = new Presentation(pptPath);
                ppt.Save(toPath, Aspose.Slides.Export.SaveFormat.Pdf);
                return toPath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    /// <summary>
    /// 扩展方法
    /// </summary>
    public static class ExtendMethon
    {
        /// <summary>
        /// 获取文件夹路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetDirectoryPath(this string path)
        {
            return Path.GetDirectoryName(path);
        }
        /// <summary>
        /// 获取文件名称
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetFileName(this string path)
        {
            return Path.GetFileName(path);
        }
    }
}
